from pathlib import Path
from pprint import pformat

import requests
from loguru import logger


def download_file(url, cookie, file, tax_org_number, tax_type, declare_month):
    if "download" not in url:
        return
    file_name = f"{tax_type}_new.xlsx"
    BASE_DIR = Path(__file__).resolve().parent.parent
    path = BASE_DIR.joinpath(f"utils/税种/{declare_month}/{tax_type}/{tax_org_number}/").joinpath(
        file_name
    )
    headers = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
    cookies = {"cas_access_token": cookie}
    data = {"fileName": file, "delFlag": "GtbtReportExcel"}
    logger.info(f"request url={pformat(url)},request data={pformat(data)}")
    response = requests.post(
        url=url, headers=headers, cookies=cookies, data=data, stream=True
    )
    if response.text == "":
        return
    with open(path, "wb") as file:
        for chunk in response.iter_content(chunk_size=8192):
            file.write(chunk)
    return path


if __name__ == "__main__":
    # Cookie = "JSESSIONID=E2B4573147824F65CC920F3711E93274; lianjia_uuid=21847742-a8ab-4cbb-a4f6-1a83dba0bcb3; lianjia_ssid=d080ce99-2134-44c0-b45d-9dad2a46b820; cas_access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX25hbWUiOiIxODAwMTA5ODc3MyIsInNjb3BlIjoiU1pZSCIsImV4cCI6MTc0NDc4Nzc0NSwianRpIjoiODVEMEQxNzk1RTczODlFRDBDMTU5QTkxNTA4NTQzNzgifQ.PtNEjqbKdh79g9_RxiwFHhnK39sXjAzGQuW7ze86pA0; JSESSIONID=444B20DA9A6BBDFDEB23689E960E76E1"
    # file_path = "/mnt/file/tmp//91120116MA05TRE02H_天津贝壳房地产经纪有限公司_2025-01_增值税一般纳税人.xlsx"
    # url_path = "https://taxcyt.ke.com/declarereport/dfg/orgGtbt/downloadFile"
    # print(download_file(url_path, Cookie, file_path, "增值税一般纳税人"))
    BASE_DIR = Path(__file__).resolve().parent.parent
    path = BASE_DIR.joinpath(f"utils/税种/增值税").joinpath("增值税_new.xlsx")
    print(path)
